package com.filter;

import com.alibaba.fastjson.JSON;
import com.conf.StringRedisUtils;
import com.util.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 〈功能简述〉
 * 〈功能详细描述〉
 *
 * @Author zhaoyifan
 * @Date 2020/4/21 10:34
 * @Since [产品/模块版本]
 * @Description TODO
 * @Version 3.0
 */
@Component
@Order
@WebFilter(urlPatterns = "/*", filterName = "requestParamFilter")
public class RequestParamFilter implements Filter {


    @Autowired
    private StringRedisUtils stringRedisUtils;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest req = (HttpServletRequest)servletRequest;
        HttpServletResponse rsp = (HttpServletResponse)servletResponse;

        if(req.getServletPath().indexOf("/mendao/v2")>=0 || req.getServletPath().indexOf("/mendao")>=0 || req.getServletPath().indexOf("/sysUser")>=0 || req.getServletPath().indexOf("/articleInfo")>=0
                || req.getServletPath().indexOf("/index")>=0 || req.getServletPath().indexOf("/picture")>=0 || req.getServletPath().indexOf("/expertCourseInfo")>=0
                || req.getServletPath().indexOf("/getSchemePdf")>=0 || req.getServletPath().indexOf("/getPrintSchemePdf")>=0 || req.getServletPath().indexOf("/recruitInfo/list")>=0|| req.getServletPath().indexOf("/open")>=0){
            filterChain.doFilter(req,rsp);
            return;
        }
        String satoken = req.getHeader("satoken");
        String userId = req.getHeader("userId");
        String terminal = req.getHeader("terminal");
        if(!StringUtils.hasText(terminal)){
            terminal = "web";
        }
        if(StringUtils.hasText(satoken) && StringUtils.hasText(userId)){
            String RedisToken = stringRedisUtils.getStringVal(userId+terminal);
            if(RedisToken == null || !satoken.equals(RedisToken)){
                rsp.setCharacterEncoding("UTF-8");
                rsp.setContentType("application/json; charset=utf-8");
                PrintWriter out = rsp.getWriter();
                R resp = R.error(402,"系统检测到您的账号已在其他地方登陆，请重新登录！");
                out.append(JSON.toJSONString(resp));
            }else{
                filterChain.doFilter(req,rsp);
            }
        }else {
            filterChain.doFilter(req,rsp);
        }
    }
    @Override
    public void destroy() {
    }
}
